import 'dart:async';
import 'dart:convert';
import 'dart:developer';
import 'dart:io';

import 'package:flutter/material.dart';

// 百度地图相关依赖
import 'package:flutter_baidu_mapapi_base/flutter_baidu_mapapi_base.dart';
import 'package:flutter_baidu_mapapi_map/flutter_baidu_mapapi_map.dart';

// 百度计算类工具包
import 'package:flutter_baidu_mapapi_utils/flutter_baidu_mapapi_utils.dart';

// 百度定位相关依赖
import 'package:flutter_bmflocation/bdmap_location_flutter_plugin.dart';
import 'package:flutter_bmflocation/flutter_baidu_location.dart';
import 'package:flutter_bmflocation/flutter_baidu_location_android_option.dart';
import 'package:flutter_bmflocation/flutter_baidu_location_ios_option.dart';

import 'constans.dart';
import 'model/geojson.dart';

void main() {
  runApp(const MyApp());
  if (Platform.isIOS) {
    BMFMapSDK.setApiKeyAndCoordType(Constans.iosKey, BMF_COORD_TYPE.BD09LL);
  } else if (Platform.isAndroid) {
    BMFMapSDK.setCoordType(BMF_COORD_TYPE.BD09LL);
  }
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  BMFMapController? controller;
  // 地图层级
  int? _zoomLevel = 13;

  // 空白地图
  BMFMapController? _emptyController;

  //地图初始化
  BMFMapOptions mapOptions = BMFMapOptions(
      // center: BMFCoordinate(39.917215, 116.380341), //默认北京
      center: BMFCoordinate(22.513194, 114.532754),
      zoomLevel: 13,
      maxZoomLevel: 18,
      mapType: BMFMapType.Standard,
      //禁用俯视仰视角
      overlookEnabled: false,
      //显示比例尺
      showMapScaleBar: true,
      //禁止旋转
      rotateEnabled: false,
      mapPadding: BMFEdgeInsets(left: 30, top: 0, right: 30, bottom: 0));

  //定位相关
  BMFLocation location = BMFLocation(
      coordinate: BMFCoordinate(39.917215, 116.380341),
      altitude: 0,
      horizontalAccuracy: 5,
      verticalAccuracy: -1.0,
      speed: -1.0,
      course: -1.0);

  BMFUserLocationDisplayParam displayParam = BMFUserLocationDisplayParam(
      locationViewOffsetX: 0,
      locationViewOffsetY: 0,
      accuracyCircleFillColor: Colors.red,
      accuracyCircleStrokeColor: Colors.blue,
      isAccuracyCircleShow: true,
      // locationViewImage: 'images/props.png',
      locationViewHierarchy:
          BMFLocationViewHierarchy.LOCATION_VIEW_HIERARCHY_BOTTOM);

  BMFCustomMapStyleOption customMapStyleOption = BMFCustomMapStyleOption(
      customMapStyleID: Constans.customMapStyleID,
      customMapStyleFilePath: Constans.customMapStyleFilePath);

  Map<String, Object>? _loationResult;
  BaiduLocation? _baiduLocation; // 定位结果

  StreamSubscription<Map<String, Object>?>? _locationListener;

  final LocationFlutterPlugin _locationPlugin = LocationFlutterPlugin();
  List<FeaturesData>? features = [];
  List<BMFGround> boundsList = List.empty(growable: true);
  // 多边形列表
  List<BMFPolygon> polygonList = List.empty(growable: true);

  /// 当前选中的多边形
  BMFPolygon? curPolygon;

  void getZoomLevel() {
    controller!.getZoomLevel().then((zoomLevel) {
      if (zoomLevel != null) {
        log('当前层级--->$zoomLevel');
        _zoomLevel = zoomLevel;
        setState(() {});
      }
    });
  }

  /// 获取map的可视范围
  void getVisibleMapBounds() {
    controller!.getVisibleMapBounds().then((BMFCoordinateBounds? bounds) {
      if (bounds != null) {
        log('当前地图的可视范围--->${bounds.toMap()}');
      }
    });
  }

  /// 创建地图回调
  void onBMFMapCreated(BMFMapController bmfMapController) async {
    controller = bmfMapController;
    controller!.getShowMapScaleBar().then((value) {
      if (value != null) {
        log('map是否显式比例尺--->$value');
      }
    });
    controller!.showBaseIndoorMap(true).then((value) {
      if (value) {
        log('展示室内地图--->成功');
      } else {
        log('展示室内地图--->失败');
      }
    });

    /// 地图加载回调
    controller!.setMapDidLoadCallback(callback: () {
      log('mapDidLoad-地图加载完成');
    });
    getZoomLevel();

    /// 点中底图标注后会回调此接口
    controller!.setMapOnClickedMapPoiCallback(callback: (BMFMapPoi mapPoi) {
      log('点中底图标注后会回调此接口poi=${mapPoi.toMap()}');
      // setState(() {
      //   _mapPoi = mapPoi;
      //   _touchPointStr = '标注触摸点';
      // });
    });

    /// 点中底图空白处会回调此接口
    controller!.setMapOnClickedMapBlankCallback(
        callback: (BMFCoordinate coordinate) {
      var startTime = DateTime.now();
      log('点中底图空白处会回调此接口coord=${coordinate.toMap()}');
      BMFPolygon? polygon = isInKnownLocation(coordinate, polygonList);
      if (polygon != null) {
        log('当前长按的坐标在表格内');
        log('长按到的方格--->${polygon.toMap()}');
        selectPolygon(polygon);
        var endTime = DateTime.now();
        log('选中方格的时间间隔---->${startTime.difference(endTime).inSeconds}s');
      } else {
        log('当前长按的坐标不在表格内');
      }
      // setState(() {
      //   _coordinate = coordinate;
      //   _mapPoi = null;
      //   _touchPointStr = '空白触摸点';
      // });
    });

    /// 双击地图时会回调此接口
    controller!.setMapOnDoubleClickCallback(
        callback: (BMFCoordinate coordinate) {
      log('双击地图时会回调此接口coord=${coordinate.toMap()}');
      // setState(() {
      //   _coordinate = coordinate;
      //   _mapPoi = null;
      //   _touchPointStr = '双击触摸点';
      // });
    });

    controller!.setMapDidFinishedRenderCallback(callback: (bool isFinish) {
      log('地图渲染之后会回调此接口===== 返回参$isFinish');
    });

    controller!.setMapOnDrawMapFrameCallback(
        callback: (BMFMapStatus mapStatus) {
      getZoomLevel();
      getVisibleMapBounds();
      log('设置地图渲染每一帧画面过程中，以及每次需要重绘地图时（例如添加覆盖物）回调接口=====mapStatus-->${mapStatus.toMap()}');
    });

    /// 长按地图时会回调此接口
    controller!.setMapOnLongClickCallback(callback: (BMFCoordinate coordinate) {
      log('长按地图时会回调此接口coord=${coordinate.toMap()}');
      // BMFPolygon? polygon = isInKnownLocation(coordinate, polygonList);
      //   log('长按到的方格--->${polygon.toMap()}');
      // if (polygon != null) {
      //   log('当前长按的坐标在表格内');
      //   selectPolygon(polygon);
      // } else {
      //   log('当前长按的坐标不在表格内');
      // }
      // setState(() {
      //   _coordinate = coordinate;
      //   _mapPoi = null;
      //   _touchPointStr = '长按触摸点';
      // });
    });
  }

  @override
  void initState() {
    super.initState();
    requestPermission();

    /// 设置ios端ak, android端ak可以直接在清单文件中配置
    LocationFlutterPlugin.setApiKey(Constans.iosKey);
    // _locationPlugin.stopLocation();
    // _locationPlugin.startLocation();
    // _locationListener = _locationPlugin
    //     .onResultCallback()
    //     .listen((Map<String, Object>? result) {
    //   setState(() {
    //     _loationResult = result;
    //     try {
    //       _baiduLocation =
    //           BaiduLocation.fromMap(result); // 将原生端返回的定位结果信息存储在定位结果类中
    //       // 获取定位后更改地图初始定位的经纬度
    //       location.coordinate = BMFCoordinate(
    //           _baiduLocation!.latitude!, _baiduLocation!.longitude!);
    //       debugPrint(jsonEncode(_baiduLocation?.getMap()));
    //     } catch (e) {
    //       debugPrint(e.toString());
    //     }
    //   });
    // });

    /// 地图加载完成后回调
    if (controller != null) {
      controller!.setMapDidLoadCallback(callback: () {
        debugPrint('地图加载完成');
      });
    }
  }

  @override
  void dispose() {
    super.dispose();
    if (null != _locationListener) {
      _locationListener?.cancel(); // 停止定位
    }
  }

  /// 获取定位权限
  void requestPermission() {
    /// 动态申请定位权限
    _locationPlugin.requestPermission();
  }

  /// 获取定位信息
  void getLocationInfo() {
    if (_loationResult != null) {
      // debugPrint('定位信息----------->' + jsonEncode(_baiduLocation?.getMap()));
      if (_loationResult != null) {
        debugPrint('获取定位信息： ---- start');
        _loationResult?.forEach((key, value) {
          debugPrint(
              'key: ' + key + " =========> " + 'value: ' + value.toString());
        });
        debugPrint('定位信息 ---- end');
      }
    }
  }

  /// 设置android端和ios端定位参数
  void _setLocOption() {
    /// android 端设置定位参数
    BaiduLocationAndroidOption androidOption = BaiduLocationAndroidOption();
    androidOption.setCoorType("WGS84"); // 设置返回的位置坐标系类型
    androidOption.setIsNeedAltitude(true); // 设置是否需要返回海拔高度信息
    androidOption.setIsNeedAddres(true); // 设置是否需要返回地址信息
    androidOption.setIsNeedLocationPoiList(true); // 设置是否需要返回周边poi信息
    androidOption.setIsNeedNewVersionRgc(true); // 设置是否需要返回最新版本rgc信息
    androidOption.setIsNeedLocationDescribe(true); // 设置是否需要返回位置描述
    androidOption.setOpenGps(true); // 设置是否需要使用gps
    androidOption.setLocationMode(LocationMode.Hight_Accuracy); // 设置定位模式
    androidOption.setScanspan(1000); // 设置发起定位请求时间间隔

    Map androidMap = androidOption.getMap();

    /// ios 端设置定位参数
    BaiduLocationIOSOption iosOption = BaiduLocationIOSOption();
    iosOption.setIsNeedNewVersionRgc(true); // 设置是否需要返回最新版本rgc信息
    iosOption.setBMKLocationCoordinateType(
        "BMKLocationCoordinateTypeWGS84"); // 设置返回的位置坐标系类型
    iosOption.setActivityType("CLActivityTypeAutomotiveNavigation"); // 设置应用位置类型
    iosOption.setLocationTimeout(15); // 设置位置获取超时时间
    iosOption.setDesiredAccuracy("kCLLocationAccuracyBest"); // 设置预期精度参数
    iosOption.setReGeocodeTimeout(15); // 设置获取地址信息超时时间
    iosOption.setDistanceFilter(100); // 设置定位最小更新距离
    iosOption.setAllowsBackgroundLocationUpdates(true); // 是否允许后台定位
    iosOption.setPauseLocUpdateAutomatically(true); //  定位是否会被系统自动暂停

    Map iosMap = iosOption.getMap();

    _locationPlugin.prepareLoc(androidMap, iosMap);
  }

  /// 启动定位
  void _startLocation() {
    _setLocOption();
    // _locationPlugin.stopLocation();
    _locationPlugin.startLocation();
  }

  /// 停止定位
  void _stopLocation() {
    _locationPlugin.stopLocation();
  }

  /// 在定位所在地添加一个marker
  void addMarker() async {
    await controller!
        .addMarker(BMFMarker(
      position: location.coordinate!,
      title: 'flutterMaker',
      identifier: 'flutter_marker',
      icon: 'images/test.png',
      scaleX: 0.5,
      scaleY: 0.5,
      enabled3D: false,
    ))
        .then((value) {
      if (value) {
        setState(() {});
        debugPrint('添加Marker--->成功');
      } else {
        debugPrint('添加Marker--->失败');
      }
    });
  }

  /// 清空所有Markers
  void cleanAllMarkers() {
    if (controller != null) {
      controller!.cleanAllMarkers().then((value) {
        if (value) {
          setState(() {});
          debugPrint('地图清除所有Markers--->成功');
        } else {
          debugPrint('地图清除所有Markers--->失败');
        }
      });
    }
  }

  /// 在定位所在地添加一个Ground
  void addTerritory(i) async {
    // BMFCoordinateBounds? visibleBounds = await controller!.getVisibleMapBounds();
    // print('test2:'+visibleBounds!.toMap().toString());

    BMFCoordinate southwest = BMFCoordinate(22.518194, 114.537754);

    /// 东北角经纬度
    BMFCoordinate northeast = BMFCoordinate(22.513194, 114.532754);

    // /// 西南角经纬度
    // BMFCoordinate southwest = BMFCoordinate(((location.coordinate!.latitude*1000000+(i*20000))-0.01*1000000)/1000000, ((location.coordinate!.longitude*1000000+(i*20000))-0.01*1000000)/1000000);
    //
    // /// 东北角经纬度
    // BMFCoordinate northeast = BMFCoordinate(((location.coordinate!.latitude*1000000+(i*20000))+0.01*1000000)/1000000, ((location.coordinate!.longitude*1000000+(i*20000))+0.01*1000000)/1000000);
    BMFCoordinateBounds bounds =
        BMFCoordinateBounds(southwest: southwest, northeast: northeast);

    // /// 构造ground
    BMFGround bmfGround = BMFGround(
        image: 'images/testbg.png', bounds: bounds, transparency: 0.3);
    //
    // print('test1:'+bmfGround.toMap().toString());
    /// 添加ground
    await controller?.addGround(bmfGround).then((value) {
      if (value) {
        setState(() {});
        debugPrint('添加Marker--->成功');
        i++;
        // if(i<10) {
        //   addTerritory(i);
        // }
      } else {
        debugPrint('添加Marker--->失败');
        i++;
        // if(i<10) {
        //   addTerritory(i);
        // }
      }
    });
  }

  /// 跳转至定位所在地
  void toLocationforMap() async {
    BMFCoordinate? value = await coordConvert(22.513194, 114.542754);
    if (controller != null) {
      late bool result;
      if (Platform.isAndroid) {
        result = await controller!
            .setNewLatLngZoom(coordinate: location.coordinate!, zoom: 4);
      } else {
        result =
            // await controller!.setCenterCoordinate(location.coordinate!, true);
            await controller!.setCenterCoordinate(value!, true);
        // BMFCoordinate(39.917215, 116.380341), true);
      }

      if (result) {
        setState(() {});
        debugPrint('跳回定位所在位置--->成功');
      } else {
        debugPrint('跳回定位所在位置--->失败');
      }
    }
  }

  /// 切换地图样式
  void customMapStyle() async {
    if (controller != null) {
      await controller!
          .setCustomMapStyle(Constans.customMapStyleFilePath, 0)
          .then((value) {
        if (value) {
          debugPrint('设置自定义地图---->成功');
        } else {
          debugPrint('设置自定义地图---->失败');
        }
      });
      controller!.setCustomMapStyleWithOptionPath(
          customMapStyleOption: customMapStyleOption,
          preload: (path) {
            debugPrint('preload');
          },
          success: (path) {
            debugPrint('设置自定义地图成功， path ----> $path');
          },
          error: (errorCode, path) {
            debugPrint('setCustomMapStyleWithOptionPath ----- errorCode:' +
                errorCode.toString() +
                '++path:' +
                path.toString());
          });
    }
  }

  Future<BMFCoordinate?> coordConvert(double latitude, double longitude) async {
    return await BMFCalculateUtils.coordConvert(
        coordinate: BMFCoordinate(latitude, longitude),
        fromType: BMF_COORD_TYPE.GPS,
        toType: BMF_COORD_TYPE.GPS);
  }

  increment(i) async {
    // log('i:' +
    //     i.toString() +
    //     '---bounds---->${boundsList[i].bounds!.toMap().toString()}');
    log('i:' +
        i.toString() +
        '---polygonList---->${polygonList[i].coordinates.toList().toString()}');
    // await controller!.addGround(boundsList[i]);
    await controller!.addPolygon(polygonList[i]);
    setState(() {});
    if (i < polygonList.length - 1) {
      // Future.delayed(const Duration(milliseconds: 200), () async {
      i = i + 1;
      increment(i);
      // });
    }
  }

  void _incrementCounter() async {
    log('boundsList length---->${boundsList.length.toString()}');

    /// 西南角经纬度
    // BMFCoordinate southwest = BMFCoordinate(22.513194, 114.532754);
    //
    // /// 东北角经纬度
    // BMFCoordinate northeast = BMFCoordinate(22.518194, 114.537754);
    // BMFCoordinateBounds bounds =
    //     BMFCoordinateBounds(southwest: southwest, northeast: northeast);
    //
    // /// 构造ground
    // BMFGround bmfGround = BMFGround(
    //     image: 'images/testbg.png', bounds: bounds, transparency: 0.3);
    //
    // /// 添加ground
    // setState(() {
    //   controller?.addGround(bmfGround);
    // });
    increment(0);
    // for (var e in boundsList) {
    //   log('bounds---->${e.bounds!.toMap().toString()}');
    //   Future.delayed(const Duration(milliseconds: 1000),() async {
    //     await controller!.addGround(e);
    //     setState(() {});
    //   });
    // }

    /// 添加ground
    // controller?.addGround(bmfGround);
    // setState(()  {
    // controller!.addPolygon(polygon)

    // 绘制多边形
    //坐标点
    // List<BMFCoordinate> coordinates = [];

    // await coordConvert(386216.2204, 2236109.8791000005)
    //     .then((value) => coordinates.add(value!));
    // await coordConvert(386212.5844999999, 2235556.4889)
    //     .then((value) => coordinates.add(value!));
    // await coordConvert(386734.9715999998, 2235553.0649999995)
    //     .then((value) => coordinates.add(value!));
    // await coordConvert(386738.59080000035, 2236106.454500001)
    //     .then((value) => coordinates.add(value!));
    // await coordConvert(386216.2204, 2236109.8791000005)
    //     .then((value) => coordinates.add(value!));
    // log('coordinates--->${coordinates.toString()}');
    // setState(() {});

    // /// 构造Polygon（多边形）
    // BMFPolygon polygon = BMFPolygon(
    //   coordinates: coordinates,
    //   width: 1, //线的宽度
    //   strokeColor: const Color(0xff46bfeb), //线的颜色
    //   fillColor: Colors.blue.withOpacity(.2), //填充颜色
    // );
    // if (controller != null) {
    //   controller!.addPolygon(polygon).then((value) {
    //     if (value) {
    //       debugPrint('添加成功');
    //     }
    //   });
    //   polygon.updateStrokeColor(const Color(0xff46bfeb));

    // controller!.updateMapOptions(BMFMapOptions(
    //     mapType: _counter % 2 == 0
    //         ? BMFMapType.Standard
    //         : BMFMapType.Satellite));
    // controller!.showUserLocation(true);
    // controller!.updateLocationData(BMFUserLocation(
    //   location: location,
    // ));
    // controller!.updateLocationViewWithParam(disp layParam);
    // }
    // });
  }

  /// 坐标是否在已知的位置列表中
  ///
  /// [coordinate] 坐标的经纬度
  /// [polygons] 已知的位置列表
  BMFPolygon? isInKnownLocation(
      BMFCoordinate coordinate, List<BMFPolygon> polygons) {
    coordinate.longitude = coordinateFormat(coordinate.longitude);
    coordinate.latitude = coordinateFormat(coordinate.latitude);
    // X轴为经度 如longitude: 114.43785176402119
    // Y轴为纬度 如latitude: 22.37322246272283
    // 在已知的位置列表中，默认false不存在
    // bool inKnownLocation = false;
    BMFPolygon? result;
    int number = 0;
    log('当前传入的坐标经纬度 -----> ${coordinate.toMap()}');
    for (var polygon in polygons) {
      // 一个多边形的经纬度数组
      List<BMFCoordinate> coordinates = polygon.coordinates;
      // 东北的经纬度
      BMFCoordinate northeast = coordinates[0];
      // 西南的经纬度
      BMFCoordinate southwest = coordinates[2];
      // List<dynamic> coordinateList = [];
      // coordinates.forEach((e) {
      //   coordinateList.add(e.toMap());
      // });
      // log('多边形的经纬度数组 -----> $coordinateList');

      // log('polygon东北的经纬度northeast-----> ${northeast.toMap()}\npolygon西南的经纬度southwest-----> ${southwest.toMap()}');
      // log('coordinate.longitude >= northeast.longitude：${coordinate.longitude >= northeast.longitude},coordinate.longitude <= southwest.longitude：${coordinate.longitude <= southwest.longitude},coordinate.latitude >= northeast.latitude：${coordinate.latitude >= northeast.latitude},coordinate.latitude <= southwest.latitude：${coordinate.latitude <= southwest.latitude}');
      if (coordinate.longitude >= northeast.longitude &&
          coordinate.longitude <= southwest.longitude &&
          coordinate.latitude >= northeast.latitude &&
          coordinate.latitude <= southwest.latitude) {
        // 当某个多边形能满足这个条件时，则表示坐标在已知的位置列表内
        // inKnownLocation = true;
        result = polygon;
        number++;
        // 结束遍历，返回结果
        // return result;
      }
    }
    log('满足条件的polygon个数：$number');
    // log('result：${result?.toMap()}');
    return result;
  }

  /// 格式化经纬度为小数点后6位数
  double coordinateFormat(double coordinate) {
    return double.parse(double.parse(coordinate.toString()).toStringAsFixed(6));
  }

  /// 选中方格时
  void selectPolygon(BMFPolygon polygon) {
    curPolygon ??= polygon;
    // 先把之前选中的方格更改为未选中状态样式
    // curPolygon?.updateStrokeColor(const Color(0xff46bfeb));
    curPolygon?.updateWidth(1);
    curPolygon?.updateFillColor(Colors.blue.withOpacity(.2));
    curPolygon?.zIndex = 1;
    // polygon.updateStrokeColor(Colors.red);
    polygon.updateWidth(3);
    polygon.updateFillColor(Colors.blue.withOpacity(.8));
    polygon.zIndex = 99;
    curPolygon = polygon;
  }

  @override
  Widget build(BuildContext context) {
    void loadData() async {
      Future<String> jsonString =
          DefaultAssetBundle.of(context).loadString('json/no1.json');
      await jsonString.then((String value) async {
        // log('value --> $value');
        Map<String, dynamic> map = json.decode(value);
        GeojsonData data = GeojsonData.fromJson(map);
        if (data.features!.isEmpty) {
          features = data.features;
        }
        // log('data.features --> ${data.features!.first.toJson()}');
        data.features?.forEach((e) {
          if (data.features!.indexOf(e) < 500) {
            var itemList = e.geometry!.rings![0];
            log('itemList --> $itemList');
            List<BMFCoordinate> coordinateList = List.empty(growable: true);
            itemList.forEach((i) {
              BMFCoordinate item = BMFCoordinate(
                  double.parse(
                      double.parse(i[1].toString()).toStringAsFixed(6)),
                  double.parse(
                      double.parse(i[0].toString()).toStringAsFixed(6)));
              coordinateList.add(item);
            });

            /// 构造Polygon（多边形）
            BMFPolygon polygon = BMFPolygon(
              coordinates: coordinateList,
              width: 1, //线的宽度
              strokeColor: const Color(0xff46bfeb), //线的颜色
              fillColor: Colors.blue.withOpacity(.2), //填充颜色
            );
            polygonList.add(polygon);

            // /// 西南角经纬度
            // BMFCoordinate southwest = BMFCoordinate(
            //     double.parse(
            //         double.parse(itemList[2][1].toString()).toStringAsFixed(6)),
            //     double.parse(double.parse(itemList[2][0].toString())
            //         .toStringAsFixed(6)));

            // /// 东北角经纬度
            // BMFCoordinate northeast = BMFCoordinate(
            //     double.parse(
            //         double.parse(itemList[0][1].toString()).toStringAsFixed(6)),
            //     double.parse(double.parse(itemList[0][0].toString())
            //         .toStringAsFixed(6)));
            // BMFCoordinateBounds bound =
            //     BMFCoordinateBounds(northeast: northeast, southwest: southwest);
            // BMFGround bmfGround = BMFGround(
            //     image: 'images/testbg.png', bounds: bound, transparency: 0.8);
            // boundsList.add(bmfGround);
          }
        });
      });
    }

    return Scaffold(
      body: Stack(
        children: <Widget>[
          // 百度地图
          BMFMapWidget(
            onBMFMapCreated: onBMFMapCreated,
            mapOptions: mapOptions,
          ),
          // 空白地图
          // Opacity(
          //   opacity: .1,
          //   child: BMFMapWidget(
          //     onBMFMapCreated: (e) {
          //       _emptyController = e;
          //       _emptyController!.showBaseIndoorMap(false);
          //     },
          //     mapOptions: emptyMapOptions,
          //   ),
          // ),

          // 按钮
          Positioned(
              right: 0,
              bottom: 80,
              child: Container(
                color: Colors.transparent,
                width: 80,
                child: Column(
                  children: <Widget>[
                    TextButton(
                      onPressed: requestPermission,
                      child: const Text('获取定位权限'),
                    ),
                    TextButton(
                      onPressed: _startLocation,
                      child: const Text('开启定位'),
                    ),
                    TextButton(
                      onPressed: _stopLocation,
                      child: const Text('停止定位'),
                    ),
                    TextButton(
                      onPressed: getLocationInfo,
                      child: const Text('获取定位信息'),
                    ),
                    TextButton(
                      onPressed: toLocationforMap,
                      child: const Text('跳至定位所在地点'),
                    ),
                    // addMarker
                    TextButton(
                      onPressed: addMarker,
                      child: const Text('在定位地点添加一个Marker'),
                    ),
                    TextButton(
                      onPressed: cleanAllMarkers,
                      child: const Text('地图清除所有Markers'),
                    ),
                    TextButton(
                      onPressed: customMapStyle,
                      child: const Text('切换自定义地图样式'),
                    ),
                    TextButton(
                      onPressed: loadData,
                      child: const Text('加载json数据'),
                    ),
                    TextButton(
                      onPressed: () {
                        addTerritory(0);
                      },
                      child: const Text('在定位地点添加一个Ground'),
                    ),
                  ],
                ),
              )),
          Positioned(
              left: 20,
              bottom: 20,
              child: Text('当前层级：$_zoomLevel',
                  style: const TextStyle(color: Colors.red))),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}
